package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.config.WxConfig;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.ThreadLocalUtil;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserRequestLoginDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IWeChatService;
import com.zzyl.nursing.vo.UserRequestLoginVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description WeChatServiceImpl
 * @Author cangyue
 * @Date 2025-07-18
 */
@Service
public class WeChatServiceImpl implements IWeChatService {
    @Autowired
    private WxConfig wxConfig;
    @Resource
    private FamilyMemberMapper familyMemberMapper;
    @Resource
    private TokenService tokenService;

    /**
     * 登录
     * @param userRequestLoginDto
     * @return
     */
    @Override
    public UserRequestLoginVo login(UserRequestLoginDto userRequestLoginDto) {
        LoginUser loginUser = new LoginUser();
        // 获取openid
        String url="https://api.weixin.qq.com/sns/jscode2session";
        Map<String,Object> param=new HashMap<>();
        param.put("appid",wxConfig.getAppId());
        param.put("secret",wxConfig.getSecret());
        param.put("js_code",userRequestLoginDto.getCode());
        String s = HttpUtil.get(url, param);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        String openid = jsonObject.getStr("openid");

        // 获取token
        url="https://api.weixin.qq.com/cgi-bin/token";
        param.clear();
        param.put("grant_type","client_credential");
        param.put("appid",wxConfig.getAppId());
        param.put("secret",wxConfig.getSecret());
        s = HttpUtil.get(url, param);
        jsonObject= JSONUtil.parseObj(s);
        String accessToken = jsonObject.getStr("access_token");
        //获取手机号
        url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
        param.clear();
        param.put("code",userRequestLoginDto.getPhoneCode());
        String jsonStr = JSONUtil.toJsonStr(param);
        String body = HttpUtil.createPost(url).body(jsonStr).execute().body();
        jsonObject = JSONUtil.parseObj(body);
        String phone = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");

        // 查询
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId , openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(queryWrapper);
        if (familyMember == null) {
            familyMember = new FamilyMember();
            familyMember.setName("ylyl");
            familyMember.setOpenId(openid);
            familyMember.setPhone(phone);
            familyMemberMapper.insertFamilyMember(familyMember);
        }

        //token
        Map<String,Object> map = new HashMap<>();
        map.put("id",familyMember.getId());
        map.put("name",familyMember.getName());
        String token = tokenService.createToken(map);
        UserRequestLoginVo userRequestLoginVo = new UserRequestLoginVo(token,familyMember.getName());
        ThreadLocalUtil.set(familyMember.getId());

        return userRequestLoginVo;
    }
}
